package com.fx.service.impl;

import cn.hutool.core.date.DateUtil;
import com.fx.entity.GoodsInfo;
import com.fx.entity.UserCart;
import com.fx.mapper.UserCartMapper;
import com.fx.service.UserCartService;
import com.fx.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service
public class UserCartServiceImpl implements UserCartService {
    @Autowired
    private UserCartMapper userCartMapper;
    @Autowired
    private IdWorker idWorker;

    @Override
    public UserCart getById(String flId) {
        return userCartMapper.getById(flId);
    }

    @Override
    public List<UserCart> getList(Map<String, Object> map) {
        return userCartMapper.queryList(map);
    }

    @Override
    public int getCount(Map<String, Object> map) {
        return userCartMapper.queryCount(map);
    }

    @Override
    public int save(UserCart userCart) {
        userCart.setFlId(String.valueOf(idWorker.nextId()));
        userCart.setFlCreatedTime(DateUtil.now());
        return userCartMapper.save(userCart);
    }

    @Override
    public int updateById(UserCart userCart) {
        return userCartMapper.updateById(userCart);
    }

    @Override
    public int remove(String flId) {
        return userCartMapper.remove(flId);
    }

    @Override
    public int batchRemove(String[] flIds) {
        return userCartMapper.batchRemove(flIds);
    }

    @Override
    public List<UserCart> getCartByUserId(String userId) {
        return userCartMapper.queryCartByUserId(userId);
    }

    @Override
    public UserCart addGoodsToCart(GoodsInfo goodsInfo, String userId, Integer quantity) {
        UserCart cart = new UserCart();
        cart.setFlCreatedTime(DateUtil.now());
        cart.setFlId(String.valueOf(idWorker.nextId()));
        cart.setFlGoodsId(goodsInfo.getFlId());
        cart.setFlName(goodsInfo.getFlName());
        cart.setFlPrice(goodsInfo.getFlSalePrice());
        cart.setFlUserId(userId);
        cart.setFlThumbnail(goodsInfo.getFlThumbnailPic());
        cart.setFlQuantity(quantity);
        cart.setFlOriginPrice(goodsInfo.getFlOriginalPrice());
        cart.setFlSubtotal(BigDecimal.valueOf(goodsInfo.getFlSalePrice().doubleValue() * quantity));
        userCartMapper.save(cart);
        return cart;
    }

    @Override
    public UserCart addQuantity(String cartId, Integer quantity) {
        UserCart userCart = userCartMapper.getById(cartId);
        userCart.setFlQuantity(quantity);
        userCart.setFlSubtotal(BigDecimal.valueOf((userCart.getFlPrice().doubleValue()*quantity)));
        userCartMapper.updateById(userCart);
        return userCart;
    }

}
